<?php

namespace Apps\Weixin\Services;


use Apps\Common\Service\BaseService;
use Deyi\Functions\HttpFunction;
use Deyi\Functions\UtilFunction;

class WxCardService extends BaseService
{
    public static $error = '';

    public function createCard($appId, $post)
    {
        $url = sprintf(
            'https://api.weixin.qq.com/card/create?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );
        $ret = HttpFunction::postDataToUrl($url, $post);
        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('create card info fail:' . $ret);
            static::$error = $ret;
            return false;
        }

        return $json->card_id;
    }

    public function uploadImgToWeixinCdn()
    {

    }

    public function getCardInfo($appId, $cardId)
    {
        $url = sprintf(
            'https://api.weixin.qq.com/card/get?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $ret = HttpFunction::postDataToUrl($url, json_encode(['card_id' => $cardId]));

        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('get card info fail:' . $appId . ', cardId:' . $cardId);
        }

        return $ret;
    }

    public function updateCard($appId, $post, $cardId)
    {
        $url = sprintf(
            'https://api.weixin.qq.com/card/update?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $ret = HttpFunction::postDataToUrl($url, json_encode($post, JSON_UNESCAPED_UNICODE));

        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('update card info fail:' . $appId . ', cardId:' . $cardId);
            return false;
        }

        return true;
    }

    /**
     * 修改库存
     * @param $appId
     * @param $cardId
     * @param int $increase_stock_value
     * @param int $reduce_stock_value
     * @return bool
     */
    public function modifyStock($appId, $cardId, $increase_stock_value = 0, $reduce_stock_value = 0)
    {
        $url = sprintf(
            'https://api.weixin.qq.com/card/modifystock?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId,
            'increase_stock_value' => $increase_stock_value,
            'reduce_stock_value' => $reduce_stock_value
        ];
        $ret = HttpFunction::postDataToUrl($url, json_encode($post));

        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('modify stock fail:' . $appId . ', cardId:' . $cardId);
            return false;
        }

        return true;
    }

    public function importCardCode($appId, $cardId, $codes)
    {
        $url = sprintf('http://api.weixin.qq.com/card/code/deposit?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId,
            'code' => $codes
        ];

        $ret = HttpFunction::postDataToUrl($url, json_encode($post));
        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('modify stock fail:' . $appId . ', cardId:' . $cardId);
            return false;
        }

        return $json;
    }

    public function countCardCode($appId, $cardId)
    {
        $url = sprintf('http://api.weixin.qq.com/card/code/getdepositcount?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId
        ];

        $ret = HttpFunction::postDataToUrl($url, json_encode($post));
        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('modify stock fail:' . $appId . ', cardId:' . $cardId);
            return false;
        }

        return $json->count;
    }

    public function verifyCardCode($appId, $cardId, $codes)
    {
        $url = sprintf('http://api.weixin.qq.com/card/code/checkcode?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId,
            'code' => $codes
        ];

        $ret = HttpFunction::postDataToUrl($url, json_encode($post));
        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->error('modify stock fail:' . $appId . ', cardId:' . $cardId);
            return false;
        }

        return $json;
    }

    /**
     * 生成 js添加到卡包 需要的 card_list 项
     * @param $appId
     * @param $cardId
     * @param null $code
     * @param null $openId
     * @param null $fixed_begintimestamp
     * @return bool|string
     */
    public function assembleJsSdkCardExtInfo($appId, $cardId, $code = null, $openId = null, $outer_id = null, $fixed_begintimestamp = null)
    {
        $timestamp = time();
        $nonceStr = md5(UtilFunction::getRandomString(6));
        $ext = [
            'code' => $code,
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr
        ];

        if ($openId) {
            $ext['openid'] = $openId;
        }

        if ($outer_id) {
            $ext['outer_id'] = $outer_id;
        }

        if ($fixed_begintimestamp) {
            $ext['fixed_begintimestamp'] = $fixed_begintimestamp;
        }

        $ext['signature'] = $this->getSignature(
            $this->getWeixinCardTicket($appId),
            $nonceStr,
            $timestamp,
            $cardId,
            $ext['code']
        );

        return json_encode([['card_id' => $cardId, 'cardExt' => json_encode($ext)]]);
    }

    /**
     * get card code status
     * @author lang@vip.deyi.com
     * @param $appId
     * @param $cardId
     * @param $code
     * @param bool $checkConsume
     * @return bool
     */
    public function getCardCodeStatus($appId, $cardId, $code, $checkConsume = true)
    {
        $url = sprintf('https://api.weixin.qq.com/card/code/get?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId,
            'code' => $code,
            'check_consume' => $checkConsume
        ];

        $ret = HttpFunction::postDataToUrl($url, json_encode($post));

        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->warning('get card code status fail:' . $appId . ', cardId:' . $cardId . ', code:' . $code . ' msg:' . $ret);
            return false;
        }

        return $json->user_card_status;
    }

    /**
     * 设置自助核销接口
     * @param $appId
     * @param $cardId
     * @param bool $isOpen
     * @param bool $needVerifyCod
     * @param bool $needRemarkAmount
     * @return bool
     */
    public function setSelfConsumeCell($appId, $cardId, $isOpen = false, $needVerifyCod = false, $needRemarkAmount = false)
    {
        $url = sprintf('https://api.weixin.qq.com/card/selfconsumecell/set?access_token=%s',
            WxResourceService::getInstance()->getAuthorizerAccessToken($appId)
        );

        $post = [
            'card_id' => $cardId,
            'is_open' => $isOpen,
            'need_verify_code' => $needVerifyCod,
            'need_remark_amount' => $needRemarkAmount
        ];

        $ret = HttpFunction::postDataToUrl($url, json_encode($post));

        if (!$ret || !($json = json_decode($ret)) || $json->errcode) {
            static::$_logger->warning('set card self consume cell fail:' . $appId . ', cardId:' . $cardId . ', msg:' . $ret);
            return false;
        }

        return true;
    }
}